package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.dubbo.pojo.UserLocation;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.dubbo.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.geo.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

@DubboService(version = "1.0.0")
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新用户地理位置
     *
     * @param userId    用户id
     * @param longitude 经度
     * @param latitude  纬度
     * @param address   地址名称
     * @return
     */
    @Override
    public Boolean updateUserLocation(Long userId, Double longitude, Double latitude, String address) {

        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = this.mongoTemplate.findOne(query, UserLocation.class);

        if (null != userLocation) {
            //更新位置数据
            Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                    .set("address", address)
                    .set("updated", System.currentTimeMillis())
                    .set("lastUpdated", userLocation.getUpdated());
            this.mongoTemplate.updateFirst(query, update, UserLocation.class);
        } else {
            //查询新的数据
            userLocation = new UserLocation();
            userLocation.setId(ObjectId.get());
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setAddress(address);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(userLocation.getCreated());
            userLocation.setLastUpdated(userLocation.getCreated());
            this.mongoTemplate.save(userLocation);
        }

        return true;
    }

    /**
     * 查询用户地理位置
     *
     * @param userId
     * @return
     */
    @Override
    public UserLocationVo queryByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = this.mongoTemplate.findOne(query, UserLocation.class);
        return UserLocationVo.format(userLocation);
    }

    /**
     * 根据位置搜索
     *
     * @param userId    用户id
     * @param longitude 经度
     * @param latitude  纬度
     * @param distance  距离(米)
     * @param page      页数
     * @param pageSize  页面大小
     */
    @Override
    public PageInfo<UserLocationVo> queryUserFromLocation(Long userId, Double longitude, Double latitude,
                                                          Double distance, Integer page,
                                                          Integer pageSize) {
        PageInfo<UserLocationVo> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //定义中心点
        Point point = new Point(longitude, latitude);

        //分页
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);

        //构建查询条件
        NearQuery nearQuery = NearQuery.near(point, Metrics.KILOMETERS)
                .maxDistance(distance / 1000).with(pageRequest);

        //查询
        GeoResults<UserLocation> geoResults = this.mongoTemplate.geoNear(nearQuery, UserLocation.class);
        if (CollUtil.isEmpty(geoResults.getContent())) {
            return pageInfo;
        }

        List<UserLocationVo> locationVoList = geoResults.getContent().stream()
                .map(result -> UserLocationVo.format(result.getContent()))
                .filter(userLocationVo -> !ObjectUtil.equal(userLocationVo.getUserId(), userId)) //过滤，排除自己
                .collect(Collectors.toList());

        pageInfo.setRecords(locationVoList);
        return pageInfo;
    }
}
